package services;

import java.util.Collection;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import repositories.ChallengeRepository;
import domain.Challenge;
import domain.Event;
@Service
@Transactional
public class ChallengeService {
	
	//Managed repository
	@Autowired
	private ChallengeRepository challengeRepository;
	
	//Supporting services
	@Autowired
	private AdministratorService administratorService;
	
	//Constructors
	public ChallengeService() {
		super();
	}
	
	//CRUD methods
	public Challenge create(Event event){
		
		Challenge result = new Challenge();
		Assert.notNull(event);
		result.setResult(null);
		result.setEvent(event);
		
		return result;
	}
	
	public Collection<Challenge> findAll(){
		Collection<Challenge> result;
		result = challengeRepository.findAll();
		return result;
	}
	
	public Challenge findOne(int challengeId){
		Challenge result;
		result = challengeRepository.findOne(challengeId);
		return result;
	}
	
	public void save(Challenge challenge){
		Date currentMoment = new Date();
		
		Assert.notNull(challenge);
		Assert.isTrue(challenge.getEvent().getAdministrator().equals(administratorService.findByPrincipal()));
		Assert.isTrue(challenge.getEvent().getStartMoment().after(currentMoment));
		
		challengeRepository.save(challenge);
	}
	
	public void delete(Challenge challenge){
		Date currentMoment = new Date();
		Assert.isTrue(challengeRepository.exists(challenge.getId()));
		Assert.isTrue(challenge.getEvent().getStartMoment().after(currentMoment));

		challengeRepository.delete(challenge);
	}
	
	
	//Other bussiness methods
	
	public Collection<Challenge> findByEventId(int id){
		Collection<Challenge> result;
		result = challengeRepository.findByEventId(id);
		return result;
	}
	
	public void addResult(Challenge challenge){
		Date currentMoment = new Date();
		Assert.isTrue(challenge.getEvent().getAdministrator().equals(administratorService.findByPrincipal()));
		Assert.isTrue(challenge.getEvent().getFinishMoment().before(currentMoment));
		Assert.isNull(challenge.getResult());
		
		challengeRepository.save(challenge);
	}
	
	
}
